package com.huilian.iotbox.data.service.impl;

import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.dao.DeviceCommonDao;
import com.huilian.iotbox.data.enums.DeviceServiceProviderEnum;
import com.huilian.iotbox.data.service.DeviceCommonService;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DeviceCommonServiceImpl implements DeviceCommonService {


    @Autowired
    private DeviceCommonDao deviceCommonDao;
    @Autowired
    private ErrorLogCommonService errorLogCommonService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public Integer getServiceProvider(String deviceNo) {
        try {
            final String key = String.format(RedisKey.DEVICE_SERVICE_PROVIDER, deviceNo);
            Integer serviceProvider = (Integer) redisCacheTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(serviceProvider)) {
                DeviceVo deviceVo = deviceCommonDao.findOneDeviceByDeviceNo(deviceNo);
                redisCacheTemplate.opsForValue().set(key, deviceVo.getServiceProvider(), 1, TimeUnit.HOURS);
                return deviceVo.getServiceProvider();
            }
            return serviceProvider;
        } catch (Exception e) {
            e.printStackTrace();
            errorLogCommonService.writerInfoException("查询设备服务商报错", deviceNo, e);
            return DeviceServiceProviderEnum.ALIYUN.getCode();
        }
    }
}
